﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.SessionState;
using Foothill.Common;
using Foothill.IoC;
using Foothill.Model;
using Foothill.Service.Session;
using Foothill.Service.UploadPhoto;

namespace Foothill.Web.PostForSale
{
    public class UploadPhotoHandler : IHttpHandler, IRequiresSessionState 
    {
        public void ProcessRequest(HttpContext context)
        {
            HttpFileCollection files = context.Request.Files;

            UploadPhotoJson uploadedPhotoJson = ProcessUploadPhoto(context);

            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
            string jsonString = jsSerializer.Serialize(uploadedPhotoJson);

            context.Response.ContentType = "text/json";
            context.Response.Write(jsonString);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        internal UploadPhotoJson ProcessUploadPhoto(HttpContext context)
        {
            UploadPhotoJson jsonResult = new UploadPhotoJson();
            
            HttpFileCollection files = context.Request.Files;

            if (files == null || files.Count == 0)
            {
                return jsonResult;
            }

            IList<UploadPhoto> currentList = GetUploadedPhotoListFromSession();

            if (currentList.Count >= GlobalSettings.MaxNumOfUploadPhotos)
            {
                return jsonResult;
            }

            HttpPostedFile file = files[0];
            IUploadFileManager uploadManager = IocContainer.GetInstance<IUploadFileManager>();

            string filePathOnServer = uploadManager.SaveFile(file);

            if (!string.IsNullOrEmpty(filePathOnServer))
            {   
                UploadPhoto photo = new UploadPhoto
                {
                    PathOnServer = Path.GetFileName(filePathOnServer),
                    AdTypeId = (int)AdType.ForSale,
                    UploadDateTime = DateTime.Now
                };

                // save the photo list to session
                SaveUploadedPhotoInstanceToSession(photo);

                jsonResult = new UploadPhotoJson
                {
                    PhotoFileName = Path.GetFileName(photo.PathOnServer)
                };
            }

            return jsonResult;
        }

        // get the photo list from the session
        private static IList<UploadPhoto> GetUploadedPhotoListFromSession()
        {
            List<UploadPhoto> retVal;
            ISessionService sessionService = IocContainer.GetInstance<ISessionService>();
            object obj = sessionService.GetSessionValue(SessionNames.ForSalePhotoList);

            if (obj == null)
            {
                // no photo has been uploaded yet
                retVal = new List<UploadPhoto>();
            }
            else
            {
                retVal = obj as List<UploadPhoto>;
            }

            return retVal;
        }

        // add the newly uploaded photo to the list of photos that user has uploaded and save the list of photo objects to session
        private void SaveUploadedPhotoInstanceToSession(UploadPhoto photo)
        {
            IList<UploadPhoto> photoList = GetUploadedPhotoListFromSession();

            int count = photoList.Count;

            if (count >= GlobalSettings.MaxNumOfUploadPhotos)
            {
                return;
            }

            photo.DisplayIndex = count;
            photoList.Add(photo);
            
            ISessionService sessionService = IocContainer.GetInstance<ISessionService>();
            
            // save the photo list to session
            sessionService.SaveSessionValue(SessionNames.ForSalePhotoList, photoList);
        }
    }
}